package org.itboys.mobile.service.mysql.mobile.wallet;

import com.google.common.collect.Maps;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.number.ToNumberUtils;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.wallet.PearlIncomRecordMapper;
import org.itboys.mobile.entity.mongo.MemberLevel;
import org.itboys.mobile.entity.mongo.OrderItem;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.order.PearlOrder;
import org.itboys.mobile.entity.mysql.wallet.PearlIncomRecord;
import org.itboys.mobile.service.mongo.mobile.OrderItemService;
import org.itboys.mobile.service.mongo.mobile.SundayMobileMemberLevelService;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.mysql.mobile.order.PearlOrderService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;


/**
 * Created on 2017/10/31.
 * @author 朱坤涛
 * 收益详情记录服务层
 */
@Service
public class PearlIncomService {

    protected Logger logger = LoggerFactory.getLogger(PearlIncomService.class);
    @Autowired
    private PearlOrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayMobileMemberLevelService memberLevelService;
    @Autowired
    private PearlIncomRecordMapper incomRecordMapper;


    public void startIncom(Long orderId){
        PearlOrder order = orderService.find(orderId);
        List<OrderItem> orderItemList = orderItemService.findByField("orderId",orderId);
        BigDecimal orderScale = new BigDecimal(0); //总佣金
        for (OrderItem oi:orderItemList){
            if (oi.getScale() ==0){
                continue;
            }
            BigDecimal totleScale = new BigDecimal(oi.getScale()*oi.getNum()); //获取商品的总佣金
            orderScale = orderScale.add(totleScale);
        }
        SundayMember member = memberService.getById(order.getMemberId());
        //上级合伙人分佣
        MemberLevel partner = memberLevelService.getByField("code", SundayCommonConstants.MemberLevelCode.PARTNER);
        SundayMember mm = memberService.getById(order.getShopId());
        //直推收益分配
        if (member.getMemberLevel()==2){
            PearlIncomRecord incomRecordMember1 = new PearlIncomRecord();
            incomRecordMember1.setObjId(orderId); //设置订单Id
            incomRecordMember1.setAmount(orderScale);
            incomRecordMember1.setMoney(orderScale);
            incomRecordMember1.setUserId(member.getId());
            incomRecordMember1.setFromUserId(member.getId());
            inster(incomRecordMember1);
            if (order.getShopId()!=0){
                PearlIncomRecord incomRecordMember2 = new PearlIncomRecord();
                incomRecordMember2.setObjId(orderId); //设置订单Id
                incomRecordMember2.setAmount(new BigDecimal(orderScale.doubleValue()*partner.getShopCommiaaion()*0.01).setScale(2,BigDecimal.ROUND_HALF_UP));
                incomRecordMember2.setMoney(new BigDecimal(orderScale.doubleValue()*partner.getShopCommiaaion()*0.01).setScale(2,BigDecimal.ROUND_HALF_UP));
                incomRecordMember2.setUserId(order.getShopId());
                incomRecordMember2.setFromUserId(member.getId());
                inster(incomRecordMember2);
            }
        }else {
            if (order.getShopId()!=null&&order.getShopId()!=0){
                PearlIncomRecord incomRecordMember1 = new PearlIncomRecord();
                incomRecordMember1.setObjId(orderId);
                incomRecordMember1.setAmount(orderScale);
                incomRecordMember1.setMoney(orderScale);
                incomRecordMember1.setUserId(order.getShopId());
                incomRecordMember1.setFromUserId(member.getId());
                inster(incomRecordMember1);
            }
        }
        if (mm!=null){
            String[] path = mm.getPath().split("/");
            //分佣
            int mLevel = mm.getMemberLevel();
            Long partnerId = 0L;
            for (int i =path.length-2;i>0;i--){
                if (StringUtils.isNotBlank(path[i])){
                    SundayMember mmm = memberService.getById(Long.parseLong(path[i]));
                    if (mLevel ==2){
                        if (mmm.getMemberLevel()==2&&member.getMemberLevel()<2){
                            partnerId =mmm.getId();
                            mLevel=2;
                        }
                    }
                }
            }
            //店主收益
            if (partnerId!=0){
                PearlIncomRecord record =new PearlIncomRecord();
                record.setObjId(orderId);
                record.setObjType(2);
                record.setAmount(new BigDecimal(orderScale.doubleValue()*partner.getShopCommiaaion()*0.01).setScale(2,BigDecimal.ROUND_HALF_UP));
                record.setMoney(new BigDecimal(orderScale.doubleValue()*partner.getShopCommiaaion()*0.01).setScale(2,BigDecimal.ROUND_HALF_UP));
                record.setUserId(partnerId);
                record.setFromUserId(member.getId());
                inster(record);
            }
        }

    }

    //开店分佣
    public void startIncomeByShop(Long memberId){
        SundayMember member = memberService.getById(memberId);
        //有推荐人
        if (member.getRecId()!=0){
            SundayMember mm = memberService.getById(member.getRecId());
            MemberLevel partner = memberLevelService.getByField("code",SundayCommonConstants.MemberLevelCode.PARTNER);
            String[] path = mm.getPath().split("/");
            if (mm.getMemberLevel() ==2){
                PearlIncomRecord record = new PearlIncomRecord();
                record.setObjId(0L);
                record.setObjType(2);
                record.setUserId(mm.getId());
                record.setIsConfirm(1);
                record.setFromUserId(member.getId());
                inster(record);
            }

        }
    }


    /**
     * 新增一条记录
     *
     * @param incomeRecord
     */

    public void inster(PearlIncomRecord incomeRecord) {
        try {
            incomRecordMapper.inster(incomeRecord);
            logger.info("IncomeRecordService.inster:insert new item", incomeRecord);
//            if(incomeRecord.getIsConfirm() == 1) {
//                //更新会员余额
//                Member member = memberService.getById(incomeRecord.getUserId());
//                member.setMoney(member.getMoney() + incomeRecord.getMoney().doubleValue());
//                memberService.update(member);
//                logger.info("member money detail = {} + {}", incomeRecord.getMoney().doubleValue(), member.getMoney());
//            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IncomeRecordService.inster fail", e);
        }

    }

    public PearlIncomRecord findById(Long id){return incomRecordMapper.findById(id);}

    /**
     * 根据自定义参数 查询收益
     *
     * @param param
     * @return
     */
    public BigDecimal getIncomeByMap(Map<String, Object> param) {
        return incomRecordMapper.getIncomeByMap(param);
    }

    /**
     * 根据自定义参数 查询累积收益
     *
     * @param param
     * @return
     */
    public BigDecimal getIncomeAmountByMap(Map<String, Object> param) {
        BigDecimal a = incomRecordMapper.getIncomeAmountByMap(param);
        return ToNumberUtils.formatNumber(a, "#.00");
    }

    public BigDecimal getIncomeWaitAmountByMap(Map<String, Object> param) {
        BigDecimal a = incomRecordMapper.getIncomeWaitAmountByMap(param);
        return ToNumberUtils.formatNumber(a, "#.00");
    }

    public List<PearlIncomRecord> findListByMap(Map<String, Object> param) {
        return incomRecordMapper.findListByMap(param);
    }

    public void deleteByOrder(Long id) {
        incomRecordMapper.deleteByOrder(id);
    }

    public Map<String, Object> getIncomeMap(Map<String, Object> paramMap) {
        // 总收益
        BigDecimal total = getIncomeAmountByMap(paramMap);
        //今日收益
        BigDecimal day = incomRecordMapper.getTodayIncomeMember(paramMap);
        //本周收益
        BigDecimal week = incomRecordMapper.getWeekDayIncomeMember(paramMap);
        //本月收益
        BigDecimal month = incomRecordMapper.getMonthIncomeMember(paramMap);
        //上月收益
        BigDecimal preMonth = incomRecordMapper.getPreMonthIncomeMember(paramMap);
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("day", day);
        result.put("week", week);
        result.put("month", month);
        result.put("preMonth", preMonth);
        return result;
    }

    /**
     * 今日收益
     *
     * @return
     */
    public BigDecimal getTodayIncomeMember(Long memberId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);

        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        return incomRecordMapper.getTodayIncomeMember(paramMap);
    }

    //本周
    public BigDecimal getWeekDayIncomeMember(Long memberId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);

        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        return incomRecordMapper.getWeekDayIncomeMember(paramMap);
    }

    //上月
    public BigDecimal getPreMonthIncomeMember(Long memberId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);

        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        return incomRecordMapper.getPreMonthIncomeMember(paramMap);
    }

    /**
     * 当月收益
     *
     * @return
     */
    public BigDecimal getMonthIncomeMember(Long memberId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);

        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        return incomRecordMapper.getMonthIncomeMember(paramMap);
    }

    public BigDecimal getMonthIncomeMember2(Long userId) {
        return incomRecordMapper.getMonthIncomeMember2(userId);
    }

    /**
     * 用户订单确认收货后批量更改收益记录状态
     *
     * @param orderId
     */
    public void doOrderConfirm(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("objId", orderId);
        List<PearlIncomRecord> list = incomRecordMapper.findListByMap(map);
        // 批量更新
        if (list != null && list.size() > 0) {
            List<Long> ids = new ArrayList<>();
            for (PearlIncomRecord incomeRecord : list) {
                if(incomeRecord.getObjType() == 1 || incomeRecord.getObjType() == 3) {
                    ids.add(incomeRecord.getUserId());
//                    if (incomeRecord.getObjType() == 1) {
//                        //更新会员余额
//                        Member member = memberService.getById(incomeRecord.getUserId());
//                        member.setMoney(member.getMoney() + incomeRecord.getMoney().doubleValue());
//                        memberService.update(member);
//                        logger.info("member money detail = {} + {}", incomeRecord.getMoney().doubleValue(), member.getMoney());
//                    }
                }
            }
            incomRecordMapper.batchUpdate(ids);
        }
    }

    /**
     * 收益详情
     *
     * @return
     */
    public List<PearlIncomRecord> findRecordDetails(Map<String, Object> map) {
        return incomRecordMapper.findRecordDetails(map);
    }

    public List<PearlIncomRecord> findListByShop(Map<String, Object> map) {
        return incomRecordMapper.findListByShop(map);
    }

    public void deleteRecord(Long id) {
        incomRecordMapper.delete(id);
    }

    //我的余额
    public BigDecimal getMoneyByMemberId(Long memberId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);
        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        paramMap.put("isConfirm", 1);

        BigDecimal total = getIncomeByMap(paramMap);

        Map<String,Object> param = Maps.newHashMap();
        param.put("sale",5);
        param.put("userId",memberId);
        BigDecimal outMoney = getIncomeByMap(param);

        return total.add(outMoney);
    }

    /**
     * 我的收益
     * @param memberId
     * @return
     */
    public Map<String, Object> getProfit(Long memberId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", memberId);

        SundayMember member = memberService.getById(memberId);
        if(member.getMemberLevel() >= 3) {
            paramMap.put("sale", 1); //收益
        } else {
            paramMap.put("objType", 1);
        }
        // 总收益
        BigDecimal totalProfit = getIncomeAmountByMap(paramMap);
        resultMap.put("totalProfit", ToNumberUtils.formatNumber(totalProfit, "#.00"));
        // 可提现金额
        paramMap.put("isConfirm", 1);
        BigDecimal totalAmount = getIncomeByMap(paramMap);
        Map<String,Object> param = Maps.newHashMap();
        param.put("sale",5);
        param.put("userId",memberId);
        BigDecimal outMoney = getIncomeByMap(param);
        //resultMap.put("withdrawAmount", ToNumberUtils.formatNumber(getIncomeByMap(paramMap), "#.00"));
        resultMap.put("withdrawAmount", totalAmount.add(outMoney));

        paramMap.clear();
        paramMap.put("userId", memberId);
        paramMap.put("objType", 1);
        paramMap.put("isConfirm", 0);
        resultMap.put("waitAmount", ToNumberUtils.formatNumber(getIncomeByMap(paramMap), "#.00"));

        paramMap.clear();

        return resultMap;
    }

    //团队提成收益
    public Map<String, Object> getTeamProfit(Long memberId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PearlIncomRecord> week = incomRecordMapper.getWeekDayIncomeType(memberId);
        List<PearlIncomRecord> preMonth = incomRecordMapper.getPreMonthIncomeType(memberId);
        List<PearlIncomRecord> month = incomRecordMapper.getMonthIncomeType(memberId);
        BigDecimal a = new BigDecimal(0);
        BigDecimal b = new BigDecimal(0);
        BigDecimal c = new BigDecimal(0);
        for (PearlIncomRecord incomeRecord : week) {
            a = a.add(incomeRecord.getAmount());
        }
        for (PearlIncomRecord incomeRecord : preMonth) {
            b = b.add(incomeRecord.getAmount());
        }
        for (PearlIncomRecord incomeRecord : month) {
            c = c.add(incomeRecord.getAmount());
        }
        System.out.println("a=" + week.size() +",b="+preMonth.size()+",c="+month.size());
        Map<String, Object> map = new HashMap<>();
        map.put("userId", memberId);
        map.put("objType", 3);
        map.put("isConfirm", 1);
        resultMap.put("total", ToNumberUtils.formatNumber(incomRecordMapper.getIncomeByMap(map), "#.00"));
        resultMap.put("week", ToNumberUtils.formatNumber(a, "#.00"));
        resultMap.put("preMonth", ToNumberUtils.formatNumber(b, "#.00"));
        resultMap.put("month", ToNumberUtils.formatNumber(c, "#.00"));
        return resultMap;
    }

    public Map<String, Object> getTeamProfitDetail(Long memberId, Integer type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PearlIncomRecord> list = null;
        BigDecimal aa = new BigDecimal(0);
        if(type == 1) {
            list = incomRecordMapper.getPreMonthIncomeType(memberId);
        } else if (type == 2){
            list = incomRecordMapper.getMonthIncomeType(memberId);
        } else {
            list = incomRecordMapper.getWeekDayIncomeType(memberId);
        }
        for (PearlIncomRecord record : list) {
            aa = aa.add(record.getAmount());
            PearlOrder order = orderService.find(record.getObjId());
            if(order != null) {
                record.setOrderNo(order.getOrderNo());
            }
            record.setAmount(ToNumberUtils.formatNumber(record.getAmount(), "#.00"));
        }
        resultMap.put("total", ToNumberUtils.formatNumber(aa, "#.00"));
        resultMap.put("list", list);
        return resultMap;
    }

    public void updateConfirm(Long memberId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("objType", 2);
        map.put("userId", memberId);
        map.put("isConfirm", 0);
        List<PearlIncomRecord> list = incomRecordMapper.findListByMap(map);
        List<Long> ids = new ArrayList<>();
        for (PearlIncomRecord record : list) {
            ids.add(record.getUserId());
        }
        if (ids.size()>0){
            incomRecordMapper.batchUpdateConfirm(ids);
        }
    }
}
